package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@MultipartConfig //必须加这个注解，开启对上传文件的支持,否则 调用 getPart()就会抛异常
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 得到文件
        Part part = req.getPart("myImage");

        // 得到当前对象
        resp.setContentType("text/json; charset=utf8");
        // 让前端检测当前的登录状态
        HttpSession session = req.getSession(false);
        if (session == null){
            // 检测会话是否存在 ,不存在则未登录
            User user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");// 会话里有没有 user对象
        if (user == null){
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        UserDao userDao = new UserDao();
        // 得到原来的路径
        String old = userDao.findPhotoByName(user.getUserName()).split(" ")[0];
        int newNum = Integer.parseInt(old.split("_")[1])+1;
        // 得到照片
        String path = "E:/gitee_program/java-ee-elementary/blog_system/src/main/webapp/image/" + user.getUserName() + "_" + newNum + ".png ";
        // 删除原来的照片
        User.deletePhoto(user.getUserName());
        // 写到存储位置
        part.write(path);
        // 更新数据库信息
        user.setPhoto(user.getUserName()+"_" + newNum);
        userDao.updateUser(user);
        // 重定向到首页
        resp.sendRedirect("list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/json; charset=utf8");
        // 让前端检测当前的登录状态
        HttpSession session = req.getSession(false);
        if (session == null){
            // 检测会话是否存在 ,不存在则未登录
            resp.getWriter().write("null");
            return;
        }
        User user = (User) session.getAttribute("user");// 会话里有没有 user对象
        if (user == null){
            resp.getWriter().write("null");
            return;
        }
        user.setPassword("");
        resp.setContentType("text/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
